package com.united.ucts.modules.auth.domain;

import com.united.frame.plugin.security.CurrUser;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;

/**
 * 基于spring-security的当前应用访问用户信息
 *
 * @author hudan
 * @version 1.0
 * @filename MyUserDetails.java
 * @copyright <a href="www.united.cn">www.united.cn</a>
 * @date 2019-10-10
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@ToString(callSuper = true)
public class MyUserDetails implements UserDetails {

    @ApiModelProperty(value = "当前登录用户ID")
    private String id;
    @ApiModelProperty(value = "当前访问用户编号/用户名")
    private String username;
    @ApiModelProperty(value = "当前访问用户密码")
    private String password;
    @ApiModelProperty(value = "当前访问用户状态")
    private Boolean enabled;
    @ApiModelProperty(value = "当前访问客户端ID(后台/前端)")
    private String clientId;
    @ApiModelProperty(value = "权限数据")
    private Collection<SimpleGrantedAuthority> authorities;

    public MyUserDetails(CurrUser currUser) {
        this.setId(currUser.getId());
        this.setUsername(currUser.getUsername());
        this.setPassword(currUser.getPassword());
        this.setEnabled(currUser.getEnable());
        this.setClientId(currUser.getClientId());

        if (CollectionUtils.isNotEmpty(currUser.getRoles())) {
            authorities = new ArrayList<>();
            currUser.getRoles().forEach(item -> authorities.add(new SimpleGrantedAuthority(item)));
        }
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.enabled;
    }
}